package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 分类信息操作
 */
@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Resource
    private SetmealService setmealService; // 套餐信息操作
    @Resource
    private DishService dishService; //菜品信息操作

    /**
     * 根据id删除分类 ,删除前进行判断
     * @param id 分类id
     */
    @Override
    public void remove(Long id) {
        //判断该分类中是否有菜品信息
        LambdaQueryWrapper<Dish> queryWrapper1 = Wrappers.lambdaQuery(Dish.class).eq(Dish::getCategoryId, id);
        //查询菜品信息
        int count1 = dishService.count(queryWrapper1);
        if (count1 > 0){
            // 该分类关联了菜品信息 抛出业务异常
            log.error("分类关联了菜品");
            throw new CustomException("该分类关联了菜品,不能删除");
        }
        //判断该分类中是否有套餐信息
        LambdaQueryWrapper<Setmeal> queryWrapper2 = Wrappers.lambdaQuery(Setmeal.class).eq(Setmeal::getCategoryId, id);
        //查询套餐信息
        int count2 = setmealService.count(queryWrapper2);
        if (count2 > 0){
            // 该分类关联了套餐信息 抛出业务异常
            log.error("分类关联了套餐");
            throw new CustomException("该分类关联了套餐,不能删除");
        }
        // 分类没有关联任何信息,可以删除
        super.removeById(id);
    }
}
